import Error from "@/views/error.vue";
import Login from "@/views/login.vue";
import Home from "@/views/home.vue";
import { getToken } from "@/utils/cache";
import { createWebHistory, createRouter, RouteRecordRaw } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { transformRoutes } from '@/utils/asyncRoutes'
import { useRouteStore } from '@/store/routeStore'
import baseService from "@/service/baseService";
import { reactive, toRef } from "vue";

// 提交表单数据
let form = toRef(
  reactive({username: ""})
);

/**
 * 框架基础路由
 */
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: Home,
    //redirect: "/sys/user",
    meta: { title: "主页" }
  },
  {
    path: "/login",
    component: Login,
    meta: { title: "登录" }
  },
  {
    path: "/error",
    name: "error",
    component: Error,
    meta: { title: "错误页面" }
  },
  {
    path: "/:path(.*)*",
    redirect: { path: "/error", query: { to: 404 }, replace: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  }
});


// 设置路由守卫
router.beforeEach((to, from, next) => {
  // 执行进度条开始加载
  NProgress.start();
  const routeStore = useRouteStore();
  const token = getToken();
  if (to.path === "/login") {
	routeStore.clearCache(); // 登录时清除缓存
    if (token){ 
	   next({ path: "/" }); 
	}
  } else {
    if(!token){ 
	   routeStore.clearCache();
	   return next({ path: "/login" }); 
	}
	
	// 已缓存且未过期（30分钟有效期）
    if(routeStore.cachedRoutes.length > 0 && Date.now() - routeStore.lastFetchTime < 1800000) {
      return next();
    }
	
	// 获取最新路由
    baseService.post(`/home/getRouteList`, form.value).then((res) => {
      if(res.code === 200) {
		const asyncRoutes = transformRoutes(res.data);
		
		// 清空旧路由
		router.getRoutes().forEach(route => {
		  if (route.name) router.removeRoute(route.name)
		})
		
		// 添加新路由
        asyncRoutes.forEach(route => router.addRoute(route)); 
        router.addRoute({path: "/login", component: Login,meta: { title: "登录" }});		
		router.addRoute({path: "/error", name: "error", component: Error, meta: { title: "错误页面" }});	
		router.addRoute({path: "/:path(.*)*", redirect: { path: "/error", query: { to: 404 }, replace: true }});
		
		// 更新缓存
        routeStore.setRoutes(asyncRoutes);
	
		next({ ...to, replace: true });	
      }
    });
	
  }
  next();
});

// 路由跳转后钩子函数中 - 执行进度条加载结束
router.afterEach(() => {
  NProgress.done();
});

export default router;
